<!--周建威-->
<!--2017/12/1-->
<template>
    <section>

        <!--头部进度条 start -->
        <el-row class="mt-10">
            <el-col :offset='0' :span='24'>
                <el-steps :active='step' simple>
                    <el-step title='商品参数'  icon="el-icon-tickets">></el-step>
                    <el-step title='商品详情'  icon="el-icon-edit">></el-step>
                    <el-step title='发布成功'  icon="el-icon-circle-check-outline">></el-step>
                </el-steps>
            </el-col>
        </el-row>
        <!--头部进度条 end -->

        <!--新增表单start -->
        <el-form :model='addForm' label-width='100px' ref='addForm' class='add-goods-form' :rules='addFormRules' v-show="step===1">
            <!--基本信息 start -->
            <el-row class="mt-10 row-padding">
                <div class="form-title">
                    基本信息
                </div>
                <el-col :offset='0' :span='24'>
                    <el-form-item label='商品分类' prop='categories'>

                        <div v-for="(category, index) in addForm.categories" class="category-content">
                              <span  >{{category.names}}
                                  <i class="el-icon-circle-close" @click="deleteCategory(index)" style="cursor: pointer"></i>
                              </span>
                        </div>
                        <el-button  size='small' @click="visible.category=true">关联新分类</el-button>
                    </el-form-item>
                    <el-form-item label='商品名称' prop='product_name'>
                        <el-input v-model='addForm.product_name' style='width: 300px' @change="handleSetKey">
                        </el-input>
                    </el-form-item>
                    <el-form-item label='商品简介' prop='product_jingle'>
                        <el-input v-model='addForm.product_jingle' @change="handleSetDescription" >
                        </el-input>
                    </el-form-item>
                    <el-form-item label='商品类型' >
                        <el-radio-group v-model='addForm.product_type'>
                            <el-radio :label='index+1' v-for="(type,index) in productType" :key="index">{{type}}</el-radio>

                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label='品牌' prop='brand'>
                        <el-select v-model='addForm.brand_id' filterable placeholder='请选择'>
                            <el-option
                                    v-for='brand in brands'
                                    :key='brand.brand_id'
                                    :label='brand.brand_name'
                                    :value='brand.brand_id'>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label='上架状态' prop='product_status'>
                        <el-radio-group v-model='addForm.product_status'>
                            <el-radio :label='1'>上架</el-radio>
                            <el-radio :label='0'>下架</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label='跨境商品' prop='is_oversea' v-show="addForm.product_type==1">
                        <el-radio-group v-model='addForm.is_oversea'>
                            <el-radio :label='0'>否</el-radio>
                            <el-radio :label='1'>是</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label='国家' prop='product_nation_id' v-show="addForm.is_oversea==1">
                        <el-select v-model="addForm.product_nation_id" filterable  placeholder="请选择">
                            <el-option
                                    v-for="item in countryList"
                                    :key="item.country_id"
                                    :label="item.country_name"
                                    :value="item.country_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label='商品图片' prop='images'>
                        <el-upload :action='productImageAction' :before-upload="beforeUpload"
                                   :on-success="onUploadSuccess"
                                   :headers="fileHeader" multiple :show-file-list="false">
                            <el-button size="small"><i class='el-icon-plus'></i></el-button>
                            <span style="color: #B4BCCC">拖动改变排序,第一张为主图</span>
                        </el-upload>

                        <div class="image-content" v-show="addForm.images.length">
                            <draggable :list="addForm.images"  v-model="addForm.images">
                                <div v-for="(image, index) in addForm.images" :key="index">
                                    <img :src="image.url" class="goods-image"/>
                                    <el-button v-on:click="removeImage(index)">删除</el-button>
                                </div>
                            </draggable>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- 基本信息end -->
            <!--价格信息 start -->
            <el-row class="mt-10 row-padding">
                <el-col :span="24">
                <div class="form-title">
                    商品价格
                </div>
                    <el-form-item label="售价" prop="product_price">
                        <el-input v-model='addForm.product_price' class="input-middle" @change="handleVIPPrice">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="VIP会员价" prop="product_vip_price">
                        <el-input v-model='addForm.product_vip_price' class="input-middle">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="原价" prop="product_market_price">
                        <el-input v-model='addForm.product_market_price'  class="input-middle">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="成本价" prop="product_cost_price">
                        <el-input v-model='addForm.product_cost_price' class="input-middle">
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <!--价格信息 end -->
            <!--seo start -->
            <el-row class="mt-10 row-padding">
                <el-col :span="24">
                <div class="form-title">
                    TDK(方便seo)
                </div>
                    <el-form-item label="title" prop="seo_title">
                        <el-input v-model='addForm.seo_title'  class="input-middle">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="description" prop="seo_description">
                        <el-input v-model='addForm.seo_description' class="input-middle">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="keyword" prop="seo_keyword">
                        <el-input v-model='addForm.seo_keyword' class="input-middle">
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <!--seo end  -->
            <!--参数设置 start -->
            <el-row class="mt-10 row-padding">
                <el-col :span="24">
                <div class="form-title">
                    参数设置
                </div>
                <div class="mb-20">
                    <el-button type="primary"  @click="handleAddParams">增加参数</el-button>
                </div>
                    <el-form-item v-for="(param, index) in addForm.params" :key="index" label="参数">
                        <el-select v-model="addForm.params[index].label" filterable allow-create placeholder="请选择" @change="updateParamValues">
                            <el-option
                                    v-for="(item, paramsIndex) in getParamsOptions"
                                    :key="item.param_id"
                                    :label="item.param_name"
                                    :value="item.param_name" :disabled="item.disabled">
                            </el-option>
                        </el-select>
                        <el-select v-model="addForm.params[index].value" allow-create  filterable placeholder="请选择">
                            <el-option
                                    v-for="item in addForm.params[index].values"
                                    :label="item"
                                    :key="index"
                                    :value="item">
                            </el-option>
                        </el-select>
                       <i class="el-icon-error delete-icon" @click="handleRemoveParam(index)"></i>
                    </el-form-item>
                </el-col>
            </el-row>
            <!--参数设置 end -->
            <!--选项设置 start -->
            <el-row class="mt-10 row-padding">
                <el-col :span="24">
                <div class="form-title">
                    商品规格
                </div>
                <div class="mb-20">
                    <el-button type="primary" @click="handleAddOption">添加规格项目</el-button>
                </div>
                    <div v-for="(option, index) in addForm.options" :key="index">
                        <el-form-item label="商品规格" class="option-item" prop="options">
                            <el-select v-model="addForm.options[index].label"   filterable placeholder="请选择" @change="updateOptionsValues">
                                <el-option
                                        v-for="item in getOptions"
                                        :key="item.option_id"
                                        :label="item.option_name"
                                        :value="item.option_name"
                                        :disabled="item.disabled"
                                >
                                </el-option>
                            </el-select>
                            <el-button  size="small" @click="showAddOption()" >新增规格</el-button>
                            <el-button  size="small" @click="showAddOptionValue(index)" v-show="addForm.options[index].label">新增规格值</el-button>
                            <i @click="handleDeleteOption(index)"  class="el-icon-error delete-icon" style="margin-left: 70%"></i>
                        </el-form-item>
                        <div class="option-values">
                            <el-checkbox-group   v-model="addForm.options[index].value" @change="showOptionsTable">
                                <el-checkbox  v-for="option in addForm.options[index].values" :label="option" :key="option">{{option}}</el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                    <div class="form-title">
                        商品库存
                    </div>
                    <el-table :data="addForm.children" stripe style="width: 100%" v-if="addForm.children.length" >
                        <el-table-column v-for="(option, index) in getSelectedOptions" :key="index" :label="option.label " >
                                <span slot-scope="scope">{{scope.row.options[index]}}</span>
                        </el-table-column>
                        <el-table-column  label="sku" column-key="index">
                            <span slot-scope="scope" >
                                <el-input  v-model="addForm.children[scope.$index].sku" ></el-input>
                            </span>
                        </el-table-column>
                        <el-table-column  label="库存" >
                             <span slot-scope="scope">
                                <el-input v-model="addForm.children[scope.$index].quantity"></el-input>
                             </span>
                        </el-table-column>
                        <el-table-column  label="预警数量">
                             <span slot-scope="scope">
                                <el-input v-model="addForm.children[scope.$index].warning_quantity"></el-input>
                             </span>
                        </el-table-column>
                        <el-table-column  label="销售价(元)">
                             <span slot-scope="scope">
                                <el-input v-model="addForm.children[scope.$index].sale_price"></el-input>
                             </span>
                        </el-table-column>
                        <el-table-column  label="原价(元)" >
                              <span slot-scope="scope">
                                <el-input v-model="addForm.children[scope.$index].market_price"></el-input>
                             </span>
                        </el-table-column>
                        <el-table-column  label="成本价(元)" >
                              <span slot-scope="scope">
                                <el-input v-model="addForm.children[scope.$index].cost_price"></el-input>
                             </span>
                        </el-table-column>
                        <el-table-column  label="会员价(元)">
                              <span slot-scope="scope">
                                <el-input v-model="addForm.children[scope.$index].vip_price"></el-input>
                             </span>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <!--选项设置 end -->
            <!--物流其他 start -->
            <el-row class="mt-10 row-padding" >
                <el-col :span="24">
                    <div class="form-title">
                        物流/其他
                    </div>
                    <el-form-item label="运费设置" prop="product_freight" v-show="addForm.product_type==1">
                        <div >
                            <el-radio v-model="freightType" :label="2">运费模板</el-radio>
                            <el-select v-model="addForm.freight_freight_id" placeholder="请选择" style='width: 300px;margin-left: 44px' :disabled="freightType==1">
                                <el-option
                                        v-for="item in freightList"
                                        :key="item.template_id"
                                        :label="item.template_name"
                                        :value="item.template_id">
                                </el-option>
                            </el-select>
                        </div>
                        <div style="margin-top: 10px">
                            <el-radio v-model="freightType" :label="1">自定义运费</el-radio>
                            <el-input v-model='addForm.product_freight' style='width: 300px;margin-left: 30px' :disabled="freightType==2">  </el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="绑定卡卷" prop="card_id" v-show="addForm.product_type==3">
                        <el-select v-model="addForm.card_id" placeholder="请选择">
                            <el-option
                                    v-for="card in cardList"
                                    :key="card.card_id"
                                    :label="card.card_name"
                                    :value="card.card_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="每人限购" prop="limit_num">
                        <el-input-number v-model="addForm.limit_num"  :min="0" ></el-input-number>

                    </el-form-item>
                    <el-form-item label="购买权限" prop="privileges">
                        <el-checkbox-group v-model="addForm.privileges">
                            <el-checkbox  :label="1">普通会员</el-checkbox>
                            <el-checkbox  :label="2">黄金会员</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="开售时间" prop="on_sale_time">
                        <div >
                            <el-radio v-model="saleType" :label="1">立即开售</el-radio>
                        </div>
                        <div style="margin-top: 10px">
                            <el-radio v-model="saleType" :label="2">定时开售</el-radio>
                            <el-date-picker v-model='addForm.on_sale_time' type="datetime" value-format="yyyy-MM-dd HH:mm:ss" style="margin-left:44px "
                                    placeholder="选择日期时间" :disabled="saleType==1">
                            </el-date-picker>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>

            <!--物流其他 end -->
        </el-form>
        <!--新增表单end-->

        <!--商品详情设置 start -->
        <el-row v-show="step===2" class="mt-10 row-padding" style="height: 800px">
            <div class="form-title">
                商品详情
            </div>
            <vue-editor v-model="addForm.description" style="margin-top: 20px;height: 600px" @imageAdded="handleImageAdded" useCustomImageHandler></vue-editor>
        </el-row>
        <!--商品详情设置 end -->

        <!--按钮start -->
        <div class="button-div">
            <el-button type='primary' @click='nextStep()' v-show="step==1" >下一步</el-button>
            <el-button type='success' @click='preStep()'  v-show="step==2" >上一步</el-button>
            <el-button  @click=''  v-show="step==2" >PC端预览</el-button>
            <el-button  @click=''  v-show="step==2" >移动端预览</el-button>
            <el-button type='primary' @click='handAddProduct()'  v-show="step==2" style="float: right" :disabled="this.handAdd  === true">发布</el-button>
        </div>
        <!--按钮end -->

        <!--新增成功 start -->
        <div class="upload-success" v-if="step==3">
            <div>
                <img src="../../assets/success.png">
                <span style="font-size: 20px">发布成功</span>
                <el-button @click="addAgain"  type="primary" class="mt-10">继续发布</el-button>
                <router-link to="/product/list" >
                    <el-button class="mt-10">商品列表</el-button>
                </router-link>
            </div>
        </div>
        <!--新增成功 end -->


        <!--关联新分类弹窗 start-->
        <el-dialog  :visible.sync="visible.category" width="400px" >
            <div slot="title" class="dialog-title">
                关联新分类
            </div>
          <el-form ref="categoryForm" :model="categoryForm">
            <el-form-item prop="categorySelected" :rules="addCategoryRules">
              <el-cascader :options="categoryOptions" v-model="categoryForm.categorySelected"  :props="categoryProps" style="width: 100%">
              </el-cascader>
            </el-form-item>
          </el-form>

            <span slot="footer" class="dialog-footer">
            <el-button @click="visible.category = false">取 消</el-button>
                <el-button type="primary" @click="handleAddCategory">确 定</el-button>
            </span>
        </el-dialog>
        <!--关联新分类弹窗 end-->

        <!--新增规格值弹窗 start-->
        <el-dialog  :visible.sync="visible.addOptionValue" width="400px" >
            <div slot="title" class="dialog-title">
                新增规格值
            </div>
            <el-input v-model="addOptionValue"></el-input>
            <span slot="footer" class="dialog-footer">
            <el-button @click="visible.addOptionValue = false">取 消</el-button>
                <el-button type="primary" @click="handleAddOptionValue">确 定</el-button>
            </span>
        </el-dialog>
        <!--新增规格值弹窗 end-->

        <!--新增规格弹窗 start-->
        <el-dialog :visible.sync="visible.addOptionKey" width="400px" >
            <div slot="title" class="dialog-title">
                新增规格
            </div>
            <el-input v-model="addOptionKey"></el-input>
            <span slot="footer" class="dialog-footer">
            <el-button @click="visible.addOptionKey = false">取 消</el-button>
                <el-button type="primary" @click="handleAddOptionKey">确 定</el-button>
            </span>
        </el-dialog>
        <!--新增规格弹窗 end-->
    </section>
</template>
<script>
  import draggable from 'vuedraggable'
  import {VueEditor} from 'vue2-editor'
  import {getCategories, getBrandList, uploadProductImage, getProductParams, getCountryList,
    getProductOptions, getFreightList, uploadDescImage, addProduct, getCardList} from '../../api/api';
  function descartes (list) {
    let point = {};
    let result = [];
    let pIndex = null;
    let tempCount = 0;
    let temp = [];
    for (let index in list) {
      if (typeof list[index] === 'object') {
        point[index] = {'parent': pIndex, 'count': 0}
        pIndex = index;
      }
    }
    if (pIndex === null) {
      return list;
    }
    while (true) {
      let index
      for (index in list) {
        tempCount = point[index]['count'];
        temp.push(list[index][tempCount]);
      }
      result.push(temp);
      temp = [];
      while (true) {
        if (point[index]['count'] + 1 >= list[index].length) {
          point[index]['count'] = 0;
          pIndex = point[index]['parent'];
          if (pIndex === null) {
            return result;
          }
          index = pIndex;
        } else {
          point[index]['count']++;
          break;
        }
      }
    }
  }
  export default {
    components: {
      draggable,
      VueEditor
    },
    data () {
      return {
        handAdd: false,
        step: 1,
        fileHeader: {
          Authorization: `Bearer ${this.$store.state.token}`
        },
        productImageAction: uploadProductImage,
        visible: {
          category: false,
          option: false,
          addOptionValue: false,
          addOptionKey: false,
          form: true
        },
        addForm: {
          brand_id: '',
          categories: [],
          product_name: '',
          product_jingle: '',
          product_type: 1,
          product_status: 1,
          is_oversea: 0,
          images: [],
          product_price: '',
          product_vip_price: '',
          product_market_price: '',
          product_cost_price: '',
          product_freight: '',
          seo_title: '',
          seo_description: '',
          seo_keyword: '',
          params: [],
          options: [],
          children: [],
          privileges: [1, 2],
          on_sale_time: '',
          limit_num: 0,
          freight_freight_id: '',
          description: '',
          product_nation_id: '',
          card_id: ''
        },
        addCategoryRules: [{required: true, message: '请输入正确的分类', trigger: 'blur'},
          {
            validator: (rules, value, callback) => {
              console.log(value);
              for (let i of this.addForm.categories) {
                console.log(i)
                console.log(value.sort().toString() === i.ids.sort().toString())
                if (value.sort().toString() === i.ids.sort().toString()) {
                  callback(new Error('该分类名称已添加'))
                }
              }
              callback()
            },
            trigger: 'blur'
          }],
        addFormRules: {
          categories: [
            {required: true, message: '请关联分类', trigger: 'blur'}
          ],
          product_name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'}
          ],
          product_jingle: [
            {required: true, message: '请输入商品简介', trigger: 'blur'}
          ],
          images: [
            {required: true, message: '请至少上传一张图片'}
          ],
          product_status: [
            {required: true, message: '请选择上架状态'}
          ],
          product_type: [
            {required: true, message: '请选择商品类型'}
          ],
          product_price: [
            {required: true, message: '请输入售价'},
            {pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入合法的金额'}
          ],
          product_vip_price: [
            {pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入合法的金额'}
          ],
          product_market_price: [
            {pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入合法的金额'}
          ],
          product_cost_price: [
            {pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入合法的金额'}
          ],
          product_freight: [
            {pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入合法的金额'}
          ]
        },
        active: 1,
        brands: [],
        tags: [],
        categoryOptions: [],
        paramsOptions: [],
        options: [],
        addOptionIndex: '',
        addOptionValue: '',
        productOptionList: [],
        addOptionKey: '',
        freightType: 1,
        freightList: [],
        saleType: 1,
        categoryProps: {
          value: 'category_id',
          label: 'category_name',
          children: 'children'
        },
        countryList: [],
        setVipPriceFlag: true,
        cardList: [],
        categoryForm: {
          categorySelected: []
        }
      };
    },
    methods: {
      // 设置默认seo_title,seo_key
      handleSetKey (value) {
        this.addForm.seo_title = value
        this.addForm.seo_keyword = value
      },
      // 设置默认seo_title
      handleSetDescription (value) {
        this.addForm.seo_description = value
      },

      // 设置价格时，使得vip价格和此一样,只有第一次设置时触发
      handleVIPPrice (value) {
        if (this.setVipPriceFlag) {
          this.addForm.product_vip_price = value
          this.setVipPriceFlag = false
        }
      },
      // 继续发布，刷新当前页面
      addAgain () {
        this.$router.go(0)
      },
      // 商品发布
      handAddProduct () {
        this.handAdd = true
        addProduct(this.addForm).then(res => {
          if (parseInt(res.status) === 1) {
            this.step = 3
          } else {
            this.$alert('上传商品失败', '错误', {type: 'error'})
            this.handAdd = false
          }
        })
      },
      // 详情上传图片
      handleImageAdded (file, Editor, cursorLocation) {
        let formData = new FormData();
        formData.append('file', file)
        uploadDescImage(formData).then(res => {
          if (parseInt(res.status) === 1) {
            Editor.insertEmbed(cursorLocation, 'image', res.data.fullUrl);
          } else {
            this.$alert('上传图片失败', '错误', {type: 'error'})
          }
        })
      },
      // 上一步
      preStep () {
        this.step = 1
      },
      // 下一步
      nextStep () {
        // 如果是自定义运费
        if (this.freightType === 1) {
          this.addForm.freight_freight_id = ''
        }
        // 如果是运费模板
        if (this.freightType === 2) {
          this.addForm.product_freight = ''
        }
        // 如果是立即发布
        if (this.saleType === 1) {
          this.addForm.on_sale_time = ''
        }
        // 如果不是跨境商品
        if (this.addForm.is_oversea === 0) {
          this.addForm.product_nation_id = ''
        }
        // 如果不是实物商品
        if (parseInt(this.addForm.product_type) !== 1) {
          this.addForm.freight_freight_id = ''
          this.addForm.is_oversea = 0
          this.addForm.product_freight = ''
          this.addForm.product_nation_id = ''
        }
        // 如果不是卡卷商品
        if (parseInt(this.addForm.product_type) !== 3) {
          this.addForm.card_id = ''
        }
        this.$refs['addForm'].validate(valid => {
          if (valid) {
            // 验证是否有设置规格
            if (this.addForm.children.length === 0) {
              this.$alert('请设置至少一种商品规格', '错误', {type: 'error'})
              return
            }
            // 验证规格信息是否填写完整
            for (let [item] of this.addForm.children.entries()) {
              for (let prop in item) {
                if (item[prop] === '') {
                  this.$alert('商品规格的所有参数必须填写完整', '错误', {type: 'error'})
                  return
                }
              }
            }
            this.step = 2
          } else {
            this.$alert('请检查参数是否输入完整', '错误', {type: 'error'})
          }
        })
      },
      // 删除分类
      deleteCategory (index) {
        this.addForm.categories.splice(index, 1)
      },
      // 处理关联新分类
      handleAddCategory () {
        this.$refs['categoryForm'].validate(valid => {
          if (valid === true) {
            let ids = this.categoryForm.categorySelected
            let names = ''
            // 通过id获取关联分类的名字
            for (let {category_id, category_name, children} of this.categoryOptions) {
              if (category_id === ids[0]) {
                names += category_name + '>'
                let levelOneChild = children
                for (let {category_id, category_name, children} of levelOneChild) {
                  if (category_id === ids[1]) {
                    names += category_name + '>'
                    let levelTwoChild = children
                    for (let {category_id, category_name} of levelTwoChild) {
                      if (category_id === ids[2]) {
                        names += category_name
                        break
                      }
                    }
                    break
                  }
                }
                break
              }
            }
            this.addForm.categories.push({ids: ids, names: names})
            this.categoryForm.categorySelected = []
            this.$refs['addForm'].validateField('categories')
            this.visible.category = false
          }
        })
      },
      // 获取运费模板列表
      handleFreightList () {
        getFreightList({pageSize: 100}).then(res => {
          this.freightList = res.data
        })
      },
      // 处理新增选项
      handleAddOptionKey () {
        if (!this.addOptionKey) {
          this.$alert('规格不能为空', '错误', {type: 'error'});
          return
        }
        this.options.unshift(
          {
            option_name: this.addOptionKey,
            option_value: ''
          }
        )
        this.visible.addOptionKey = false
      },
      // 显示新增选项表格
      showAddOption () {
        this.visible.addOptionKey = true
        this.addOptionKey = ''
      },
      // 显示选项表格,计算产品种类
      showOptionsTable () {
        let values = []
        for (let {value} of this.addForm.options) {
          if (value.length > 0) {
            values.push(value)
          }
        }
        let productOptionList = descartes(values)
        this.addForm.children = []
        for (let i = 0; i <= productOptionList.length - 1; i++) {
          this.addForm.children.push({
            sku: '',
            quantity: 999,
            sale_price: this.addForm.product_price,
            vip_price: this.addForm.product_vip_price,
            market_price: this.addForm.product_market_price,
            cost_price: this.addForm.product_cost_price,
            warning_quantity: 20,
            options: productOptionList[i]
          })
        }
        this.productOptionList = productOptionList
        console.log(this.addForm.children)
      },
      // 处理新增规格值
      handleAddOptionValue () {
        if (!this.addOptionValue) {
          this.$alert('规格值不能为空', '错误', {type: 'error'});
          return
        }
        this.addForm.options[this.addOptionIndex].values.push(this.addOptionValue)
        this.visible.addOptionValue = false
      },

      // 显示新增规格值
      showAddOptionValue (index) {
        this.addOptionValue = ''
        this.visible.addOptionValue = true
        this.addOptionIndex = index
      },

      // 删除商品选项
      handleDeleteOption (index) {
        this.addForm.options.splice(index, 1)
        this.showOptionsTable()
      },
      // 商品参数选修改变
      updateParamValues (key) {
        let values
        for (let [index, {param_name}] of this.paramsOptions.entries()) {
          if (param_name === key) {
            if (this.paramsOptions[index].param_value) {
              values = JSON.parse(this.paramsOptions[index].param_value)
            } else {
              values = []
            }
            break
          }
        }
        for (let [index, {label}] of this.addForm.params.entries()) {
          if (label === key) {
            this.addForm.params[index].values = values
            this.addForm.params[index].value = ''
            break
          }
        }
      },
      // 商品规格选修改变
      updateOptionsValues (key) {
        let values
        for (let [index, {option_name}] of this.options.entries()) {
          if (option_name === key) {
            if (this.options[index].option_value) {
              values = JSON.parse(this.options[index].option_value)
            } else {
              values = []
            }
            break
          }
        }
        for (let [index, {label}] of this.addForm.options.entries()) {
          if (label === key) {
            this.addForm.options[index].values = values
            this.addForm.options[index].value = []
            break
          }
        }
        this.showOptionsTable()
      },
      // 新增商品选项
      handleAddOption () {
        this.addForm.options.push({label: '', value: [], values: []})
      },
      // 获取商品选项
      handleOptions () {
        getProductOptions({pageSize: 1000}).then(res => {
          if (parseInt(res.status) === res.status) {
            this.options = res.data;
          }
        })
      },
      // 移除参数
      handleRemoveParam (index) {
        this.addForm.params.splice(index, 1)
      },
      // 新增参数
      handleAddParams () {
        this.addForm.params.push({label: '', value: '', values: []})
      },
      // 商品参数列表获取
      handleParamsOptions () {
        getProductParams({pageSize: 1000}).then(res => {
          if (parseInt(res.status) === 1) {
            this.paramsOptions = res.data
          }
        })
      },
      // 移除商品图片
      removeImage (index) {
        this.addForm.images.splice(index, 1)
        this.$refs['addForm'].validateField('images')
      },
      // 获取分类
      handleCategories () {
        getCategories({category_level: 1}).then(res => {
          this.categoryOptions = res.data;
        })
      },
      // 上传文件成功钩子
      onUploadSuccess (response, file, fileList) {
        this.addForm.images.push({path: response.data.path, url: response.data.fullUrl})
        this.$refs['addForm'].validateField('images')
      },
      // 获取国家列表
      handleCountryList () {
        getCountryList({pageSize: 300}).then(res => {
          this.countryList = res.data
        })
      },
      // 获取品牌列表
      handleBrandList () {
        getBrandList({pageSize: 1000}).then(res => {
          this.brands = res.data;
        });
      },
      // 获取卡卷列表
      handleCardList () {
        getCardList({pageSize: 1000}).then(res => {
          this.cardList = res.data
        })
      },
      // 上传文件验证
      beforeUpload (file) {
        if (file.size > 1024 * 1000) {
          this.$alert('图片大小必须小于5m', '错误', {type: 'error'})
          return false
        }
        if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
          this.$alert('图片格式必须是PNG,JPG', '错误', {type: 'error'})
          return false
        }
      }
    },
    computed: {
      // 过滤已选为空的规格
      getSelectedOptions () {
        let options = []
        for (let [index, {value}] of this.addForm.options.entries()) {
          if (value.length > 0) {
            options.push(this.addForm.options[index])
          }
        }
        return options;
      },
      // 让已选的参数disabled
      getParamsOptions () {
        for (let [index, param] of this.paramsOptions.entries()) {
          for (let addParam of this.addForm.params) {
            if (param.param_name === addParam.label) {
              this.paramsOptions[index].disabled = true
              break
            }
            this.paramsOptions[index].disabled = false
          }
        }
        return this.paramsOptions;
      },
      // 让已选的规格disabled
      getOptions () {
        for (let [index, option] of this.options.entries()) {
          for (let addOption of this.addForm.options) {
            if (option.option_name === addOption.label) {
              this.options[index].disabled = true
              break
            }
            this.options[index].disabled = false
          }
        }
        return this.options;
      },
      // 商品类型
      productType () {
        return this.$store.getters.productType
      }
    },
    mounted () {
      this.handleFreightList()
      this.handleOptions()
      this.handleParamsOptions()
      this.handleCategories()
      this.handleCountryList()
      this.handleBrandList()
      this.handleCardList()
    }
  };
</script>
<style rel='stylesheet/sass' lang='sass' scoped>
    $inputWidth: 300px
    .upload-success
        /*margin-top: 400px*/
        text-align: center
        vertical-align: middle
        div
            display: inline-block
            width: 100px
    .form-title
        margin: 20px 0
        padding-bottom: 5px
        font-size: 18px
        border-bottom: 1px solid #DFE4ED
    .button-div
        padding-bottom: 200px
        text-align: right
        margin-top: 30px
        button
            width: 100px
            margin-left: 20px
    .category-content
        display: inline-block
        margin-left: 10px
        span
            background-color: #f5f5f5
            display: inline-block
            padding: 0 5px
    .row-padding
        padding: 0 20px 20px 20px
    hr
        border-style: dashed
        border-color: #DFE4ED
    .mt-10
        margin-top: 10px
    .mb-20
        margin-bottom: 20px
    .add-goods-form
        .input-larger
            width: 500px
        .input-middle
            width: $inputWidth
        .notice
            color: #8c939d
            margin-left: 10px
        .main-img
            position: absolute
            left: 0
            width: 148px
            height: 148px
            background-color: #fbfdff
            border: 1px dashed #c0ccda
            border-radius: 6px
        .add-icon
            color: red
            margin-left: 20px
            cursor: pointer

    .center
        text-align: center
    .image-content
        margin-top: 20px
        div
            display: inline-block
            div
                width: 156px
                vertical-align: top
                text-align: center
                position: relative
                .goods-image
                    border-radius: 6px
                    box-sizing: border-box
                    width: 148px
                    height: 148px
                button
                    width: 148px
                    height: 28px
                    font-size: 16px
                    vertical-align: top
                    line-height: 28px
                    cursor: pointer
                    padding: 0
    .el-steps
        background-color: #ffffff
    .option-item
        background-color: #f4f5fa
        padding: 10px 0px
    .option-values
        padding: 0 0 20px 20px

    .delete-icon
        cursor: pointer
</style>

